package org.springblade.modules.admin.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseEntity;
import org.springblade.core.tenant.annotation.TenantIgnore;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.admin.entity.MaintainCheckGuide;
import org.springblade.modules.admin.entity.MaintainCheckGuideType;
import org.springblade.modules.admin.service.MaintainCheckGuideService;
import org.springblade.modules.admin.service.MaintainCheckGuideTypeService;
import org.springblade.modules.admin.vo.CheckGuideTypeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Date 14:48 2021/12/22
 * @Description {
 *   CheckGuideTypeController
 * }
 * @Author lsay
 **/
@RestController
@RequestMapping("/check/guide/type")
public class CheckGuideTypeController {

	@Autowired
	private MaintainCheckGuideTypeService checkGuideTypeService;
	@Autowired
	private MaintainCheckGuideService checkGuideService;

	@GetMapping("/tree")
	@TenantIgnore
	public R<List<CheckGuideTypeVO>> tree(){
		return R.data(checkGuideTypeService.tree());
	}

	@PostMapping()
	public R<Boolean> save(@RequestBody MaintainCheckGuideType checkGuideType){
		return R.data(checkGuideTypeService.save(checkGuideType));
	}

	@PutMapping()
	public R<Boolean> update(@RequestBody MaintainCheckGuideType checkGuideType){
		return R.data(checkGuideTypeService.updateById(checkGuideType));
	}

	@DeleteMapping
	public R<HashMap<String,Object>> remove(Long id){
		HashMap<String,Object> resultMap = new HashMap<>(2);
		List<Long> guideTypeIds = checkGuideTypeService.listChildIdsByParentId(id);
		guideTypeIds.add(id);
		int count = checkGuideService.count(Wrappers.<MaintainCheckGuide>lambdaQuery().in(MaintainCheckGuide::getTypeId, guideTypeIds));
		boolean result = false;
		if(count <= 0){
			result = checkGuideTypeService.remove(Wrappers.<MaintainCheckGuideType>lambdaQuery().eq(MaintainCheckGuideType::getId,id).or().eq(MaintainCheckGuideType::getParentId,id));
		}else {
			resultMap.put("desc","当前分类下有"+count+"个内容，无法删除");
		}
		resultMap.put("result", result);
		return R.data(resultMap);
	}

}
